from flask import Flask, request, jsonify
import json
from flask_cors import CORS
from CONNECT_MYSQL import Connect_MySQL

app = Flask(__name__)


class Server:
    def __init__(self, app):
        self.sql_username = None
        self.sql_password = None
        self.app = app
        self.cors = CORS(self.app)

    def get_mysql_data(self):
        # 获取数据库数据
        connect_mysql = Connect_MySQL()
        connect_mysql.select()
        result = connect_mysql.result
        for row in result:
            self.sql_username = row[0]
            self.sql_password = row[1]
        connect_mysql.format_sql_data()
        self.sql_data = connect_mysql.formatted_result

    def login(self):
        if request.method == 'OPTIONS':
            response = self.app.response_class(
                response=json.dumps({'success': True}),
                status=200,
                mimetype='application/json'
            )
        elif request.method == 'POST':
            # 获取用户输入数据
            data = request.get_json()
            username = data.get('username')
            password = data.get('password')
            # 登录匹配判断
            if username == "admin" and password == "123":
                response = jsonify({'success': True, 'message': 'Login successful', 'sql_data': self.sql_data})
            elif username == self.sql_username and password == self.sql_password:
                response = jsonify({'success': True, 'message': 'sql successful', 'sql_data': self.sql_data})
            else:
                response = jsonify({'fail': False, 'message': 'Login fail'})
        return response


server = Server(app)


@app.route('/login', methods=['POST', 'OPTIONS'])
def login():
    return server.login()


if __name__ == '__main__':
    app.run()
